package cn.guozeyiblog.netutils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.ls.LSInput;

import android.R.menu;
import crittercism.android.l;
import crittercism.android.m;
import cn.guozeyiblog.blogutils.ArticleDetail;
import cn.guozeyiblog.blogutils.BlogUtils;
import cn.guozeyiblog.blogutils.Category;
import cn.guozeyiblog.blogutils.Link;
import cn.guozeyiblog.blogutils.Wechat;

public class JsoupUtils {
	
	
	public static String GetBlogTitle(String result){
		if (result==null||result.equals("")) {
			return "枯等街寒又何妨";
		}
		Document document = Jsoup.parse(result);
		return document.title();
	}
	
	
	/**
	 * 获取友情链接
	 * @param result
	 * @return
	 */
	public static ArrayList<Link> GetLinkList(String result) {
		ArrayList<Link> listdata = new ArrayList<>();
		if (result==null||result.equals("")) {
			return listdata;
		}
		Document doc = Jsoup.parse(result);
		Elements m = doc.getElementsByAttributeValue("id", "link");
		if (m==null) {
			return listdata;
		}
		Element childs = m.first();
		if(childs==null){
			return listdata;
		}
		Elements child = childs.children();
		for (Element c:child) {
			System.out.println(c.text());
			Element hrefElement = c.select("a").first();
            if(hrefElement==null){
            	continue;
            }
            System.out.println(hrefElement.attr("href"));
            Link link = new Link(c.text(), hrefElement.attr("href"));
            listdata.add(link);
		}
		return listdata;
	}
	/**
	 * 获取分类列表
	 * @param m
	 */
	public static ArrayList<Category> GetCateList(String result){
		ArrayList<Category> listdata = new ArrayList<>();
		if (result==null||result.equals("")) {
			return listdata;
		}
		Document doc = Jsoup.parse(result);
		Elements m = doc.getElementsByAttributeValue("id", "blogsort");
		if (m==null) {
			return listdata;
		}
		Element childs = m.first();
		if(childs==null){
			return listdata;
		}
		Elements child = childs.children();
		for (Element c:child) {
			System.out.println(c.text());
            Element hrefElement = c.select("a").first();
            System.out.println(hrefElement.attr("href"));
            Category cat = new Category(c.text(), hrefElement.attr("href"));
            listdata.add(cat);
		}
		return listdata;
	}
	
	
	/**
	 * 获取文章列表
	 * @param result
	 * @return
	 * @throws IOException
	 */
	public static ArrayList<BlogUtils> GetArticleList(String result) throws IOException{
		ArrayList<BlogUtils> list = new ArrayList<>();
		if (result==null||result.equals("")) {
			return list;
		}
		Document doc = Jsoup.parse(result);
		Element m = doc.getElementById("contentleft");
		if (m==null) {
			list.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.CONTENT, "可能该文章设有访问密码,不允许查看"));
			return list; //导致的原因有可能是文章需要访问权限
		}
		Element m2 = m.removeClass("comment-post");
		if (m2==null) {
			list.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.CONTENT, "可能该文章设有访问密码,不允许查看"));
			return list; //导致的原因有可能是文章需要访问权限
		}
        //标题
        list.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.TITLE, m2.select("h2").text()));
        Elements ms = m2.children();
        list.addAll(doGetBlog(ms));
        return list;
	}
	/**
	 * 把从网络获取到的数据通过Jsuop解析处理
	 * @param result
	 * @return
	 */
	public static ArrayList<BlogUtils> doGetBlog(Elements c) throws IOException{
		ArrayList<BlogUtils> itemArrayList = new ArrayList<>();
        for(Element mElement:c){
        	String tag = mElement.nodeName();
        	if (!mElement.hasText()&&tag.equals("p")&&!mElement.hasClass("tag")) {
              itemArrayList.addAll(doGetBlog(mElement.children()));
			}
        	if (mElement.hasText()&&tag.equals("p")&&!mElement.hasClass("tag")&&!mElement.hasClass("date")) {
        		//System.out.println("P:"+mElement.text());
        		itemArrayList.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.CONTENT, mElement.text()));
  			}
        	if (tag.equals("pre")) {
				//System.out.println("CODE:"+mElement.outerHtml());
				itemArrayList.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.CODE, mElement.outerHtml()));
			}
        	if (tag.equals("a")) {
				//System.out.println("IMG:"+mElement.attr("href"));
        		if (mElement.hasText()) {
        			itemArrayList.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.CONTENT, mElement.text()));
				}else {
					itemArrayList.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.IMG, mElement.attr("href")));	
				}
				
			}
        	if (tag.equals("embed")) {
        		//System.out.println("EMBED:"+mElement.attr("src"));
        		itemArrayList.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.FLASH, mElement.attr("src")));
			}
        	if (tag.equals("div")) {
        		if (!mElement.hasClass("nextlog")&&!mElement.hasClass("pagenavi")
        				&&!mElement.hasClass("comment-place")&&!mElement.hasClass("comment-post")
        				&&!mElement.hasClass("cancel-reply")&&(!mElement.attr("id").equals("comment-place"))) {
        			itemArrayList.add(new BlogUtils(BlogUtils.DEF_BLOG_ITEM_TYPE.CONTENT, mElement.text()));
				}
			}
        }
        return itemArrayList;
	}
	
	
	/**
	 * 获取博客列表
	 * @param c
	 * @return
	 */
	public static ArrayList<ArticleDetail> GetBlogList(String result){
		ArrayList<ArticleDetail> list=new ArrayList<>();
		if (result==null||result.equals("")) {
			return list;
		}
		Document doc = Jsoup.parse(result);
		Element c = doc.getElementById("contentleft");
		
		if (c==null) {
			return list;
		}
		String alldata = c.text();
		String[] itemdataString = alldata.split("阅读全文>>");
		Elements mElements = c.select("p.date") ;
		if (mElements==null||mElements.size()==0) {
			return list;
		}
		String[] datearray = new String[mElements.size()];
		String[] titlearray = new String[mElements.size()];
		String[] titlelinkarray = new String[mElements.size()];
		String[] contentarray = new String[mElements.size()];
		String[] viewcountarray = new String[mElements.size()];
		String[] comcountarray = new String[mElements.size()];
		for (int index=0;index<mElements.size();index++) {
			Element m = mElements.get(index);
			String startString = m.text();
			//System.out.println("Start:"+startString);
			Pattern p = Pattern.compile("\\d{4}-\\d{1,2}-\\d{1,2}");
			Matcher ma = p.matcher(m.text());
			while (ma.find()) {
				//System.out.println("date:"+ma.group());   //截取的时间
				datearray[index] = ma.group();
			}
			String[] itemdata = itemdataString[index].split(startString);
			//System.out.println("content:"+itemdata[1]); //文章描述
			contentarray[index] = itemdata.length>1?itemdata[1]:"获取文章详情失败,请点击查看";
		}
		Elements mElements2 = c.select("p.count") ;
		Elements mElements3 = c.select("h2") ;
		for (int index=0;index<mElements2.size();index++) {
			Element m = mElements2.get(index);
			//System.out.println(m.text());
			String countString = m.text().trim();
			String[] conStrings = countString.split(" ");
			viewcountarray[index] = conStrings[1];
			comcountarray[index] = conStrings[0];
		}
		for (int index=0;index<mElements3.size();index++) {
			Element m = mElements3.get(index);
			//System.out.println(m.text());
			titlearray[index] = m.text();
			Element m2 = m.child(0);
			//System.out.println(m2.attr("href"));
			titlelinkarray[index] = m2.attr("href");
		}
		for (int i = 0; i < mElements.size(); i++) {
			ArticleDetail detail = new ArticleDetail();
			detail.setCommentCount(comcountarray[i]);
			detail.setDate(datearray[i]);
			detail.setDescription(contentarray[i]);
			detail.setId(Integer.parseInt(titlelinkarray[i].substring(titlelinkarray[i].lastIndexOf("=")+1, titlelinkarray[i].length())));
			detail.setLink(titlelinkarray[i]);
			detail.setViewCount(viewcountarray[i]);
			detail.setTitle(titlearray[i]);
			list.add(detail);
		}
		return list;
	}
	
	public static ArrayList<Wechat> getWechats(String result){
		ArrayList<Wechat> list = new ArrayList<>();
		if (result==null||result.equals("")) {
			return list;
		}
		Document doc = Jsoup.parse(result);
		Element c =  doc.getElementById("tw");
		String userString = null;
		if (c==null) {
			return list;
		}
		Elements m = c.select("div.post1");
		for (Element a:m) {
			for (Element b:a.children()) {
				String Tag = b.nodeName();
				if (Tag.equals("span")) {
					System.out.println(b.text());
					userString = b.text().trim();
				}
			}
            String content = a.text().trim();
            System.out.println(content.substring(userString.length(), content.length()).trim());
            Wechat wechat = new Wechat();
            wechat.setContent(content.substring(userString.length(), content.length()).trim());
            wechat.setUser(userString);
		    list.add(wechat);
		}
		return list;
	}
}
